package com.ruoyi.project.common;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.ruoyi.common.utils.pay.AlipayUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.domain.SysAliPay;
import com.ruoyi.project.common.domain.Trade;
import com.ruoyi.project.system.mapper.SysAliPayMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("/pay/ali")
@Slf4j
public class ALiPayController extends BaseController {

    @Autowired
    private SysAliPayMapper aliPayMapper;

    private SysAliPay model;

    private void initConfig() throws AlipayApiException {
        AliPayApiConfig aliPayApiConfig;
        model = aliPayMapper.selectMainConfig();
        aliPayApiConfig = AliPayApiConfig.builder()
                .setAppId(model.getAppId())
                .setAliPayPublicKey(model.getPublicKey())
                .setCharset("UTF-8")
                .setPrivateKey(model.getPrivateKey())
                .setServiceUrl(model.getGatewayUrl())
                .setSignType("RSA2");

        if (AlipayUtils.SECRET_MODE.equals(model.getMode())) {
            aliPayApiConfig.build();
        } else {
            aliPayApiConfig = aliPayApiConfig
                    .setAppCertPath(model.getCertPath())
                    .setAliPayCertPath(model.getPublicCertpath())
                    .setAliPayRootCertPath(model.getRootCertPath())
                    .buildByCert();
        }
        AliPayApiConfigKit.putApiConfig(aliPayApiConfig);
    }


    /**
     * PC支付
     */
    @PostMapping(value = "/pc")
    @ResponseBody
    public void pc(HttpServletResponse response, @RequestBody Trade trade) throws AlipayApiException {
        initConfig();
        try {
            String totalAmount = trade.getTotalAmount();
            String returnUrl = model.getReturnUrl();
            String notifyUrl = model.getNotifyUrl();
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(trade.getOutTradeNo());
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setTotalAmount(totalAmount);
            model.setSubject(trade.getSubject());
            model.setBody(trade.getBody());
            model.setPassbackParams("passback_params");
            AliPayApi.tradePage(response, "GET", model, notifyUrl, returnUrl);
        } catch (Exception e) {
            log.error("支付宝支付异常-----", e);
        }

    }

    @RequestMapping(value = "/return_url")
    @ResponseBody
    public String returnUrl(HttpServletRequest request) {
        try {
            // 获取支付宝GET过来反馈信息
            Map<String, String> map = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
            boolean verifyResult = AlipaySignature.rsaCheckV1(map, model.getPublicKey(), "UTF-8",
                    "RSA2");
            if (verifyResult) {
                // TODO 请在这里加上商户的业务逻辑程序代码
                System.out.println("return_url 验证成功");
                return "success";
            } else {
                System.out.println("return_url 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    @RequestMapping(value = "/notify_url")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request) {
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);

            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
            boolean verifyResult = AlipaySignature.rsaCheckV1(params, model.getPublicKey(), "UTF-8", "RSA2");
            if (verifyResult) {
                // TODO 请在这里加上商户的业务逻辑程序代码 异步通知可能出现订单重复通知 需要做去重处理
                System.out.println("notify_url 验证成功succcess");
                return "success";
            } else {
                System.out.println("notify_url 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

}
